package com.sora.pipeline.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sora.pipeline.common.api.ApiResponse;
import com.sora.pipeline.domain.*;
import com.sora.pipeline.domain.dto.*;
import com.sora.pipeline.service.*;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 消缺管理控制器
 * 
 * @author system
 * @since 2025-01-20
 */
@RestController
@RequestMapping("/api/remedy")
@Validated
public class RemedyController {

    @Autowired
    private RemedyTaskService remedyTaskService;
    
    @Autowired
    private RemedyMaterialService remedyMaterialService;
    
    @Autowired
    private DefectService defectService;
    
    @Autowired
    private LineService lineService;
    
    @Autowired
    private DefectLevelService defectLevelService;
    
    @Autowired
    private DefectTypeService defectTypeService;
    
    @Autowired
    private UserService userService;

    /**
     * 1. 获取整改任务列表
     * 分页获取整改任务列表，支持搜索和筛选，返回包含类型名和等级名的详细信息
     */
    @GetMapping("/tasks")
    public ApiResponse<IPage<RemedyTaskWithDetailsDTO>> getRemedyTasks(
            @RequestParam int pageNum,
            @RequestParam int pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String level,
            @RequestParam(required = false) Long defectId,
            @RequestParam(required = false) Long lineId,
            @RequestParam(required = false) Long assigneeId) {
        
        LambdaQueryWrapper<RemedyTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RemedyTask::getDeleted, false);
        
        // 搜索条件
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                .like(RemedyTask::getTaskNo, keyword)
                .or()
                .like(RemedyTask::getDescription, keyword)
            );
        }
        
        // 状态筛选
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(RemedyTask::getStatus, status);
        }
        
        // 等级筛选
        if (StringUtils.hasText(level)) {
            // 将前端传递的英文等级值转换为等级ID
            Integer levelId = null;
            switch (level) {
                case "general":
                    levelId = 1;
                    break;
                case "serious":
                    levelId = 2;
                    break;
                case "urgent":
                    levelId = 3;
                    break;
            }
            if (levelId != null) {
                queryWrapper.eq(RemedyTask::getLevelId, levelId);
            }
        }
        
        // 缺陷ID筛选
        if (defectId != null) {
            queryWrapper.eq(RemedyTask::getDefectId, defectId);
        }
        
        // 线路ID筛选
        if (lineId != null) {
            queryWrapper.eq(RemedyTask::getLineId, lineId);
        }
        
        // 负责人ID筛选
        if (assigneeId != null) {
            queryWrapper.eq(RemedyTask::getAssigneeId, assigneeId);
        }
        
        queryWrapper.orderByDesc(RemedyTask::getCreateTime);
        
        IPage<RemedyTask> page = remedyTaskService.page(new Page<>(pageNum, pageSize), queryWrapper);
        
        // 转换为包含详细信息的DTO
        IPage<RemedyTaskWithDetailsDTO> resultPage = page.convert(task -> {
            RemedyTaskWithDetailsDTO dto = RemedyTaskWithDetailsDTO.fromRemedyTask(task);
            
            // 获取缺陷信息（包含类型信息）
            if (task.getDefectId() != null) {
                Defect defect = defectService.getById(task.getDefectId());
                if (defect != null && !defect.getDeleted()) {
                    dto.setDefectCode(defect.getCode());
                    dto.setDefectTypeId(defect.getTypeId());
                    
                    // 获取缺陷类型名称
                    if (defect.getTypeId() != null) {
                        DefectType defectType = defectTypeService.getById(defect.getTypeId());
                        if (defectType != null && defectType.getEnabled()) {
                            dto.setDefectTypeName(defectType.getTypeName());
                        }
                    }
                }
            }
            
            // 获取线路信息
            if (task.getLineId() != null) {
                Line line = lineService.getById(task.getLineId());
                if (line != null && !line.getDeleted()) {
                    dto.setLineCode(line.getLineCode());
                    dto.setLineName(line.getLineName());
                }
            }
            
            // 获取缺陷等级信息
            if (task.getLevelId() != null) {
                DefectLevel defectLevel = defectLevelService.getById(task.getLevelId());
                if (defectLevel != null && defectLevel.getEnabled()) {
                    dto.setLevelName(defectLevel.getLevelName());
                }
            }
            
            // 获取负责人信息
            if (task.getAssigneeId() != null) {
                User assignee = userService.getById(task.getAssigneeId());
                if (assignee != null && !assignee.getDeleted()) {
                    dto.setAssigneeName(assignee.getName());
                    dto.setAssigneeUsername(assignee.getUsername());
                }
            }
            
            return dto;
        });
        
        return ApiResponse.success(resultPage);
    }

    /**
     * 2. 获取整改任务详情
     * 根据ID获取整改任务详细信息
     */
    @GetMapping("/tasks/{id}")
    public ApiResponse<RemedyTask> getRemedyTask(@PathVariable Long id) {
        RemedyTask task = remedyTaskService.getById(id);
        if (task == null || task.getDeleted()) {
            return ApiResponse.failure(404, "整改任务不存在");
        }
        return ApiResponse.success(task);
    }

    /**
     * 3. 创建整改任务
     * 创建新的整改任务
     */
    @PostMapping("/tasks")
    public ApiResponse<RemedyTask> createRemedyTask(@Valid @RequestBody RemedyTaskRequest request) {
        // 检查缺陷是否存在
        Defect defect = defectService.getById(request.getDefectId());
        if (defect == null || defect.getDeleted()) {
            return ApiResponse.failure(404, "缺陷不存在");
        }
        
        // 检查线路是否存在
        if (request.getLineId() != null) {
            Line line = lineService.getById(request.getLineId());
            if (line == null || line.getDeleted()) {
                return ApiResponse.failure(404, "线路不存在");
            }
        }
        
        // 检查负责人是否存在
        if (request.getAssigneeId() != null) {
            User assignee = userService.getById(request.getAssigneeId());
            if (assignee == null) {
                return ApiResponse.failure(404, "负责人不存在");
            }
        }
        
        // 生成任务编号
        String taskNo = generateTaskNo();
        
        RemedyTask task = new RemedyTask();
        BeanUtils.copyProperties(request, task);
        task.setTaskNo(taskNo);
        task.setStatus(StringUtils.hasText(request.getStatus()) ? request.getStatus() : "pending");
        task.setCreateTime(LocalDateTime.now());
        task.setUpdatedAt(LocalDateTime.now());
        task.setDeleted(false);
        
        remedyTaskService.save(task);
        
        // 保存材料
        if (request.getMaterials() != null && !request.getMaterials().isEmpty()) {
            saveMaterials(task.getId(), request.getMaterials());
        }
        
        return ApiResponse.success(task);
    }

    /**
     * 4. 更新整改任务
     * 更新整改任务信息
     */
    @PutMapping("/tasks/{id}")
    public ApiResponse<RemedyTask> updateRemedyTask(@PathVariable Long id, @Valid @RequestBody RemedyTaskRequest request) {
        RemedyTask task = remedyTaskService.getById(id);
        if (task == null || task.getDeleted()) {
            return ApiResponse.failure(404, "整改任务不存在");
        }
        
        // 检查缺陷是否存在
        Defect defect = defectService.getById(request.getDefectId());
        if (defect == null || defect.getDeleted()) {
            return ApiResponse.failure(404, "缺陷不存在");
        }
        
        // 检查线路是否存在
        if (request.getLineId() != null) {
            Line line = lineService.getById(request.getLineId());
            if (line == null || line.getDeleted()) {
                return ApiResponse.failure(404, "线路不存在");
            }
        }
        
        // 检查负责人是否存在
        if (request.getAssigneeId() != null) {
            User assignee = userService.getById(request.getAssigneeId());
            if (assignee == null) {
                return ApiResponse.failure(404, "负责人不存在");
            }
        }
        
        BeanUtils.copyProperties(request, task);
        task.setUpdatedAt(LocalDateTime.now());
        
        remedyTaskService.updateById(task);
        
        // 更新材料
        if (request.getMaterials() != null) {
            updateMaterials(id, request.getMaterials());
        }
        
        return ApiResponse.success(task);
    }

    /**
     * 5. 删除整改任务
     * 删除指定整改任务
     */
    @DeleteMapping("/tasks/{id}")
    public ApiResponse<Void> deleteRemedyTask(@PathVariable Long id) {
        RemedyTask task = remedyTaskService.getById(id);
        if (task == null || task.getDeleted()) {
            return ApiResponse.failure(404, "整改任务不存在");
        }
        
        task.setDeleted(true);
        task.setUpdatedAt(LocalDateTime.now());
        remedyTaskService.updateById(task);
        
        return ApiResponse.success(null);
    }

    /**
     * 6. 分配整改任务
     * 分配整改任务给指定人员
     */
    @PostMapping("/tasks/{id}/assign")
    public ApiResponse<Void> assignTask(@PathVariable Long id, @Valid @RequestBody RemedyTaskAssignRequest request) {
        RemedyTask task = remedyTaskService.getById(id);
        if (task == null || task.getDeleted()) {
            return ApiResponse.failure(404, "整改任务不存在");
        }
        
        // 检查负责人是否存在
        User assignee = userService.getById(request.getAssigneeId());
        if (assignee == null) {
            return ApiResponse.failure(404, "负责人不存在");
        }
        
        task.setAssigneeId(request.getAssigneeId());
        task.setDeadline(request.getDeadline());
        task.setDescription(request.getDescription());
        task.setStatus("assigned");
        task.setStartTime(LocalDateTime.now());
        task.setUpdatedAt(LocalDateTime.now());
        
        remedyTaskService.updateById(task);
        return ApiResponse.success(null);
    }

    /**
     * 7. 批量分配任务
     * 批量分配多个整改任务
     */
    @PostMapping("/tasks/batch-assign")
    public ApiResponse<Void> batchAssignTasks(@Valid @RequestBody BatchRemedyTaskAssignRequest request) {
        List<RemedyTask> tasks = remedyTaskService.listByIds(request.getTaskIds());
        if (tasks.isEmpty()) {
            return ApiResponse.failure(404, "没有找到要分配的任务");
        }
        
        // 检查负责人是否存在
        User assignee = userService.getById(request.getAssigneeId());
        if (assignee == null) {
            return ApiResponse.failure(404, "负责人不存在");
        }
        
        // 批量更新任务
        tasks.forEach(task -> {
            task.setAssigneeId(request.getAssigneeId());
            task.setDeadline(request.getDeadline());
            task.setDescription(request.getDescription());
            task.setStatus("assigned");
            task.setStartTime(LocalDateTime.now());
            task.setUpdatedAt(LocalDateTime.now());
        });
        
        remedyTaskService.updateBatchById(tasks);
        return ApiResponse.success(null);
    }

    /**
     * 8. 完成任务
     * 标记整改任务为已完成
     */
    @PostMapping("/tasks/{id}/complete")
    public ApiResponse<Void> completeTask(@PathVariable Long id, @Valid @RequestBody RemedyTaskCompleteRequest request) {
        RemedyTask task = remedyTaskService.getById(id);
        if (task == null || task.getDeleted()) {
            return ApiResponse.failure(404, "整改任务不存在");
        }
        
        if (!"assigned".equals(task.getStatus()) && !"in_progress".equals(task.getStatus())) {
            return ApiResponse.failure(400, "只有已分配或进行中的任务才能完成");
        }
        
        task.setStatus("completed");
        task.setCompleteTime(request.getCompleteTime());
        task.setProgress(request.getProgress());
        task.setDescription(request.getDescription());
        task.setImagesJson(request.getImagesJson());
        task.setUpdatedAt(LocalDateTime.now());
        
        remedyTaskService.updateById(task);
        
        // 保存材料
        if (request.getMaterials() != null && !request.getMaterials().isEmpty()) {
            saveMaterialsFromComplete(id, request.getMaterials());
        }
        
        return ApiResponse.success(null);
    }

    /**
     * 9. 获取任务材料列表
     * 获取指定任务的材料列表
     */
    @GetMapping("/tasks/{id}/materials")
    public ApiResponse<List<RemedyMaterial>> getTaskMaterials(@PathVariable Long id) {
        RemedyTask task = remedyTaskService.getById(id);
        if (task == null || task.getDeleted()) {
            return ApiResponse.failure(404, "整改任务不存在");
        }
        
        LambdaQueryWrapper<RemedyMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RemedyMaterial::getRemedyId, id);
        queryWrapper.orderByAsc(RemedyMaterial::getCreatedAt);
        
        List<RemedyMaterial> materials = remedyMaterialService.list(queryWrapper);
        return ApiResponse.success(materials);
    }

    /**
     * 10. 获取任务统计信息
     * 获取整改任务统计数据
     */
    @GetMapping("/statistics")
    public ApiResponse<Map<String, Object>> getTaskStatistics() {
        LambdaQueryWrapper<RemedyTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RemedyTask::getDeleted, false);
        
        long totalTasks = remedyTaskService.count(queryWrapper);
        
        // 按状态统计
        queryWrapper.clear();
        queryWrapper.eq(RemedyTask::getDeleted, false).eq(RemedyTask::getStatus, "pending");
        long pendingCount = remedyTaskService.count(queryWrapper);
        
        queryWrapper.clear();
        queryWrapper.eq(RemedyTask::getDeleted, false).eq(RemedyTask::getStatus, "assigned");
        long assignedCount = remedyTaskService.count(queryWrapper);
        
        queryWrapper.clear();
        queryWrapper.eq(RemedyTask::getDeleted, false).eq(RemedyTask::getStatus, "in_progress");
        long inProgressCount = remedyTaskService.count(queryWrapper);
        
        queryWrapper.clear();
        queryWrapper.eq(RemedyTask::getDeleted, false).eq(RemedyTask::getStatus, "completed");
        long completedCount = remedyTaskService.count(queryWrapper);
        
        queryWrapper.clear();
        queryWrapper.eq(RemedyTask::getDeleted, false).eq(RemedyTask::getStatus, "closed");
        long closedCount = remedyTaskService.count(queryWrapper);
        
        Map<String, Object> statistics = Map.of(
            "totalTasks", totalTasks,
            "pending", pendingCount,
            "assigned", assignedCount,
            "inProgress", inProgressCount,
            "completed", completedCount,
            "closed", closedCount
        );
        
        return ApiResponse.success(statistics);
    }

    /**
     * 生成任务编号
     */
    private String generateTaskNo() {
        String prefix = "RT-" + LocalDateTime.now().getYear() + "-";
        LambdaQueryWrapper<RemedyTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(RemedyTask::getTaskNo, prefix)
                   .orderByDesc(RemedyTask::getTaskNo)
                   .last("LIMIT 1");
        
        RemedyTask lastTask = remedyTaskService.getOne(queryWrapper);
        if (lastTask == null) {
            return prefix + "001";
        }
        
        String lastTaskNo = lastTask.getTaskNo();
        String numberPart = lastTaskNo.substring(prefix.length());
        int nextNumber = Integer.parseInt(numberPart) + 1;
        return prefix + String.format("%03d", nextNumber);
    }

    /**
     * 保存材料
     */
    private void saveMaterials(Long taskId, List<RemedyTaskRequest.MaterialInfo> materials) {
        List<RemedyMaterial> materialList = materials.stream().map(materialInfo -> {
            RemedyMaterial material = new RemedyMaterial();
            material.setRemedyId(taskId);
            material.setName(materialInfo.getName());
            material.setQuantity(materialInfo.getQuantity());
            material.setUnit(materialInfo.getUnit());
            material.setNote(materialInfo.getNote());
            material.setCreatedAt(LocalDateTime.now());
            return material;
        }).collect(Collectors.toList());
        
        remedyMaterialService.saveBatch(materialList);
    }

    /**
     * 更新材料
     */
    private void updateMaterials(Long taskId, List<RemedyTaskRequest.MaterialInfo> materials) {
        // 删除原有材料
        LambdaQueryWrapper<RemedyMaterial> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(RemedyMaterial::getRemedyId, taskId);
        remedyMaterialService.remove(deleteWrapper);
        
        // 保存新材料
        if (!materials.isEmpty()) {
            saveMaterials(taskId, materials);
        }
    }

    /**
     * 保存完成请求中的材料
     */
    private void saveMaterialsFromComplete(Long taskId, List<RemedyTaskCompleteRequest.MaterialInfo> materials) {
        List<RemedyMaterial> materialList = materials.stream().map(materialInfo -> {
            RemedyMaterial material = new RemedyMaterial();
            material.setRemedyId(taskId);
            material.setName(materialInfo.getName());
            material.setQuantity(materialInfo.getQuantity());
            material.setUnit(materialInfo.getUnit());
            material.setNote(materialInfo.getNote());
            material.setCreatedAt(LocalDateTime.now());
            return material;
        }).collect(Collectors.toList());
        
        remedyMaterialService.saveBatch(materialList);
    }
}